<?php

namespace App\Http\Controllers\VideoAdmin;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Admin\BaseController;
use App\Library\UpTools;
use App\Library\wxOpen\WeChatApi;
use App\Models\video\BroadcasterModel;
use App\Models\video\CommonServer;
use App\Models\video\SubscribeLibraryModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\WxServer;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class SettingController extends BaseController
{
    private $field = [
        "style" => [
            "operate_mode" => '1', "wxapp_title" => 'require', "wxapp_color" => '#00AAFF', "carousel_status" => 1, "list_show_mode" => '1',
            'home_font_color' => '#909399', 'home_show_mode' => '1', 'video_show_mode' => '1'
        ],
        "configs" => [
            "app_id" => 'require', "app_secret" => 'require', "mch_id" => null, "mch_key" => null, "payment_cert" => null, "payment_key" => null,
            "wx_mini_upload_key" => null, "wx_service_provider_ticket" => null, "can_ios_pay" => 0, "qq_app_id" => "", "qq_app_secret" => ""
        ],
        "tencent" => ["secret_id" => 'require', "secret_key" => 'require', "vod_key" => null, "screen_shot" => 10, "vod_class_id" => 0],
        "review" => ["review_status" => '0', "review_content" => null],
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = [
        "wxapp_title" => '小程序标题', "app_id" => '小程序AppId', "app_secret" => '小程序Secret', "mch_id" => null, "mch_key" => null, "secret_id" => '访问密钥ID', "secret_key" => '访问密钥key'
    ];
    public function __construct(Request $request){
        parent::__construct($request);
    }

    // 配置列表
    public function getDataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $type = $request->type ?: "style";
        if(empty($this->field[$type])){
            return $this->return_result(ErrorCode::code("customized", "type参数错误"));
        };
        $returnData = VideoSettingModel::getFields(array_keys($this->field[$type]), ["mall_id" => $request->mallData["id"]]);
        foreach ($this->field[$type] as $k => $v){
            if(!isset($returnData[Str::camel($k)])){
                $returnData[Str::camel($k)] = $v;
            }
        }
        if($type == 'review' && !empty($returnData["reviewContent"])){
            $returnData["reviewContent"] = json_decode($returnData["reviewContent"], true);
            $returnData["reviewContent"]["picUrl"] = isset($returnData["reviewContent"]["picId"]) ? $returnData["reviewContent"]['picId'] : "";
            $returnData = array_merge($returnData, is_array($returnData["reviewContent"]) ? $returnData["reviewContent"] : []);
        }elseif($type == 'style'){
            if(isset($returnData["operateMode"]) && $returnData["operateMode"] == '1'){
                $data = BroadcasterModel::getFields("list_show_mode,wxapp_color,wxapp_title,home_show_mode,video_show_mode,home_font_color", ["mall_id" => $request->mallData["id"], "status" => 1]);
                if(!empty($data)){
                    $returnData = array_merge($returnData, $data);
                }
            }
        }elseif($type == 'tencent'){
            $returnData["vodCallbackUrl"] = CommonServer::getUrl("/videoApi/eventNotify");
        }elseif($type == 'configs'){
            $returnData["wxMiniServerUrl"] = ['https://vod2.qcloud.com', CommonServer::getUrl()];
            $returnData["canIosPay"] = $returnData['canIosPay'] ? true : false;
            $res = file_get_contents("https://update.netbcloud.com/public/index.php/wxApp/getIp");
            $result = json_decode(trim($res, chr(239) . chr(187) . chr(191)), true);
            $returnData['uploadIp'] = $result['data']['ip'];
        }
        $this->returnData["data"] = $returnData;
        return $this->return_result($this->returnData);
    }

    // 更新
    public function updateData(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $data = [];
        if($request->type == 'review'){
            $params = $request->post();
            $data['review_status'] = isset($params["reviewStatus"]) ? $params["reviewStatus"] : '0';
            unset($params["reviewStatus"]);
            $data['review_content'] = json_encode($params, JSON_UNESCAPED_UNICODE);
        }else {
            foreach ($this->field[$request->type] as $k => $v) {
                $ks = Str::camel($k);
                if ($v === "require" && !$request->$ks) {
                    return $this->return_result(ErrorCode::code("params_not_exist", $this->fieldMsg[$k]));
                }
                $data[$k] = $request->post($ks, $v);
            }
        }
        if(isset($data['can_ios_pay'])){
            $data['can_ios_pay'] = $data['can_ios_pay'] === false ? 0 : 1;
        }
        $settingData = VideoSettingModel::getFields("id,operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($request->type == 'style'){
            if(empty($settingData["operateMode"]) || $settingData["operateMode"] == '1'){
                $i = BroadcasterModel::doUpdate([
                    'list_show_mode' => $data['list_show_mode'], 'wxapp_color' => $data['wxapp_color'], 'wxapp_title' => $data['wxapp_title'],
                    'home_show_mode' => $data['home_show_mode'], 'video_show_mode' => $data['video_show_mode'], 'home_font_color' => $data['home_font_color'],
                ], ["mall_id" => $request->mallData["id"], "status" => 1]);
            }
        }
        if(isset($data["app_id"]) && isset($data["app_secret"])){
            $response = UpTools::curl(WeChatApi::$weChat_conf["get_token"]."?grant_type=client_credential&appid={$data["app_id"]}&secret={$data["app_secret"]}");
            $result = json_decode($response, true);
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                $this->returnData["code"] = $result['errcode'];
                $this->returnData["msg"] = isset(WeChatApi::$wxChatCode[$result["errcode"]]) ? WeChatApi::$wxChatCode[$result["errcode"]] : $result["errmsg"];
                return $this->returnData;
            }
        }
        if(!empty($settingData)) {
            $res = VideoSettingModel::doUpdate($data, ["mall_id" => $request->mallData["id"]]);
        }else{
            $data["mall_id"] = $request->mallData["id"];
            $res = VideoSettingModel::toAdd($data);
        }
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '更新失败';
        }else {
            if(!empty($data["operate_mode"]) && $data["operate_mode"] == '1'){
                $tmp = BroadcasterModel::getFields("id", ["mall_id" => $request->mallData["id"], "status" => 1], true, false);
                BroadcasterModel::doUpdate(["status" => 2], [["mall_id", '=', $request->mallData["id"]], ["id", "<>", !empty($tmp["id"]) ? $tmp["id"] : 0]]);
            }
            $this->returnData['msg'] = "更新成功";
        }
        return $this->return_result($this->returnData);
    }

    public function getMemberSetting(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $returnData = VideoSettingModel::getFields("member_discount,protocol_title,protocol_content,open_member", ["mall_id" => $request->mallData["id"]], true, false);
        $this->returnData["data"] = $returnData;
        return $this->return_result($this->returnData);
    }

    public function saveMemberSetting(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(isset($request->memberDiscount)){
            $data["member_discount"] = $request->memberDiscount;
        }
        if($request->protocolTitle){
            $data["protocol_title"] = $request->protocolTitle;
        }
        if($request->protocolContent){
            $data["protocol_content"] = $request->protocolContent;
        }
        if(isset($request->openMember)){
            $data["open_member"] = $request->openMember;
        }
        if(!empty($data)){
            VideoSettingModel::doUpdate($data, ["mall_id" => $request->mallData["id"]]);
        }
        return $this->return_result($this->returnData);
    }

    // 生成订阅消息
    public function generateSubscribe(Request $request){
        $settingData = VideoSettingModel::getFields("app_id,app_secret", ["mall_id" => $request->mallData["id"]], true, false);
        if(!$settingData["appId"] || !$settingData["appSecret"]){
            return $this->return_result(ErrorCode::code("customized", "小程序未配置"));
        }
        $token = WxServer::getInstance($settingData["appId"], $settingData["appSecret"])->getToken();
        if(isset($token["code"])){
            return $this->return_result($token);
        }
        $delUrl = "https://api.weixin.qq.com/wxaapi/newtmpl/deltemplate?access_token={$token}";
        $addUrl ="https://api.weixin.qq.com/wxaapi/newtmpl/addtemplate?access_token={$token}";

        $libraryData = [];
        $library = SubscribeLibraryModel::getFields("id,template_id,type", ["mall_id" => $request->mallData["id"]], false, true);
        foreach ($library as $item){
            if($item["templateId"]) {
                UpTools::curl($delUrl, json_encode(["priTmplId" => $item["templateId"]]));
            }
            if($item["type"]){
                $libraryData[$item["type"]] = ["id" => $item["id"]];
            }
        }
        // 创建 订阅动态通知提醒
        $result = UpTools::curl($addUrl, json_encode(["tid" => "3678", "kidList" => [1,4,5,2], "sceneDesc" => "订阅新动态提醒"]));
        $result = json_decode($result, true);
        if($result['errcode'] == 0) {
            if(!empty($libraryData[SubscribeLibraryModel::DYNAMIC_REMIND])){
                SubscribeLibraryModel::doUpdate(["template_id" => $result['priTmplId']], ["id" => $libraryData[SubscribeLibraryModel::DYNAMIC_REMIND]["id"]]);
            }else{
                SubscribeLibraryModel::toAdd(["template_id" => $result['priTmplId'], "type" => SubscribeLibraryModel::DYNAMIC_REMIND]);
            }
        }
        return $this->return_result($this->returnData);
    }
}
